# 编写一个简单的脚本去实现监控服务自动化地对consul的一个注册
#!/bin/bash



#注册服务
function register_service()
{
	cat $1 | while read line
	do
		group_name=$(echo $line | awk '{print $1}')
		cluster_name=$(echo $line | awk '{print $2}')
		service_ip=$(echo $line | awk '{print $3}')
		service_port=$(echo $line | awk '{print $4}')
cat >service-$service_ip-$service_port.json<<-EOF
{	
	"id":"service-${service_ip}-${service_port}",
	"name":"service-${service_ip}-${service_port}",
	"address":"${service_ip}",
	"port":${service_port},
	"tags":["$cluster_name"],
	"meta":
	{
		"group":"$group_name",
		"cluster":"$cluster_name",
		"instance_name":"$service_ip:$service_port"
	},
	"checks":[{
		"http":"http://${service_ip}:$service_port/metrics",
		"interval":"5s"
	}],
	"Weights": {
		"Passing": 10,
		"Warning": 1
	},
	"EnableTagOverride": false
}
EOF
	curl --request PUT --data @service-$service_ip-$service_port.json \
	http://${consul_host}:${consul_http_api_port}/v1/agent/service/register?replaceexisting-checks=1
	rm -rf service-$service_ip-$service_port.json
	done
}
#注销服务
function deregister_service()
{
	cat $1 | while read line
	do
	service_ip=$(echo $line | awk '{print $3}')
	service_port=$(echo $line | awk '{print $4}')
#let service_port=redis_port+10000
	consul_service_id="service-$service_ip-$service_port"
	curl --request PUT http://${consul_host}:${consul_http_api_port}/v1/agent/service/deregister/${consul_service_id}
	done
}
#检查服务
check_service()
{
	cat $1 | while read line
	do
		service_ip=$(echo $line | awk '{print $3}')
		service_port=$(echo $line | awk '{print $4}')

#let service_port=redis_port+10000
		consul_service_id="service-$service_ip-$service_port"
		ret1=$(curl -s http://${consul_host}:${consul_http_api_port}/v1/agent/service/$consul_service_id?pretty)
		if [[ $ret1 =~ "unknown proxy service ID" ]];then
		      echo "不存在服务$consul_service_id"
		else
		      ret2=$(curl -s http://${consul_host}:${consul_http_api_port}/v1/health/service/service-$service_ip-$service_port?pretty \
		      | grep "$service_ip:$service_port/metrics: 200 OK")
		      if [[ -z "$ret2" ]];then
			echo -e "\033[5;34m服务$consul_service_id已注册,但服务状态异常 <---\033[0m"
		      else
			echo "服务$consul_service_id已注册,且服务状态正常"
                      fi
	        fi
	done
}

function main()
{
	if [[ $# -ne 2 ]];then
	echo -e "must two parameters:\nfirst exec_command(check_service or register_service or deregister_service)\nsecond filename"
	exit
	else
	      case $1 in
	     check_service)
		shift 1
	     	check_service $1
		;;
	     register_service)
		shift 1
		register_service $1
		;;
	     deregister_service)
		shift 1
		deregister_service $1
		;;
	     *)
		echo "无效的指令"
	     esac
	fi
}

consul_host="192.168.68.146"
consul_http_api_port=8500

main $1 $2
